package com.freewater.springboot.demo.core.resolvabletype.eg4;

import com.freewater.springboot.demo.core.resolvabletype.eg3.Converter;
import com.freewater.springboot.demo.core.resolvabletype.eg3.StrToIntConverter;
import com.freewater.springboot.demo.core.resolvabletype.eg3.StrToNumConverter;
import org.springframework.core.ResolvableType;

import java.lang.reflect.TypeVariable;

// 类型参数类型的兼容性测试；
public class Example<T> {

    public static void main(String[] args) {
        // 定义泛型类
        class Generic<T> {
        }

        // 定义两个TypeVariable
        TypeVariable<?> var1 = Example.class.getTypeParameters()[0];
        TypeVariable<?> var2 = Generic.class.getTypeParameters()[0];

        // 创建ResolvableType对象
        ResolvableType type1 = ResolvableType.forType(var1);
        ResolvableType type2 = ResolvableType.forType(var2);

        // 检查类型兼容性
        boolean assignable = type1.isAssignableFrom(type2);

        // 打印结果为true，原因是type1 和type2 都解析为Object.class
        System.out.println(assignable); // true

        // 下面的owner1和owner2都是ParameterizedType。包含了一个名为“T”的泛型类型参数，并且根据实现类分别解析为Integer.class和Number.class
        ResolvableType owner1 = ResolvableType.forClass(Converter.class, StrToIntConverter.class);
        ResolvableType owner2 = ResolvableType.forClass(Converter.class, StrToNumConverter.class);
        ResolvableType type3 = ResolvableType.forType(var1, owner1);
        ResolvableType type4 = ResolvableType.forType(var2, owner2);

        // type3中类型变量T解析为Integer.class，type4中类型变量T解析为Number.class，因此，type4不能赋值给type3，type3可以赋值给type4
        assignable = type3.isAssignableFrom(type4);
        System.out.println(assignable); // false
        assignable = type4.isAssignableFrom(type3);
        System.out.println(assignable);// true
    }
}
